window.addEventListener('load', e => {
  const canvas = document.getElementById('canvas');
  const gl = getWebGLContext(canvas);
  initShaders(gl, v_shader_source, f_shader_source);

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  let position = new Float32Array([
    0.0, 0.5, -0.4, 0.4, 1.0, 0.4, -0.5, -0.5, -0.4, 0.4, 1.0, 0.4, 0.5, -0.5, -0.4, 1.0, 0.4, 0.4,
    0.5, 0.4, -0.2, 1.0, 0.4, 0.4, -0.5, 0.4, -0.2, 1.0, 1.0, 0.4, 0.0, -0.6, -0.2, 1.0, 1.0, 0.4,
    0.0, 0.5, 0.0, 0.4, 0.4, 1.0, -0.5, -0.5, 0.0, 0.4, 0.4, 1.0, 0.5, -0.5, 0.0, 1.0, 0.4, 0.4
  ]);
  let FSIZE = position.BYTES_PER_ELEMENT;

  let vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, position, gl.STATIC_DRAW);

  let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 5 * FSIZE, 0);
  gl.enableVertexAttribArray(a_Position);

  let a_Color = gl.getAttribLocation(gl.program, 'a_Color');
  gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, 5 * FSIZE, 2 * FSIZE);
  gl.enableVertexAttribArray(a_Color);

  let viewMatrix = new Matrix4();
  let u_ProjMatrix = gl.getUniformLocation(gl.program, 'u_ProjMatrix');
  let [g_near, g_far] = [0.0, 0.5];
  const draw = () => {
    viewMatrix.setOrtho(-1, 1, -1, 1, g_near, g_far);
    gl.uniformMatrix4fv(u_ProjMatrix, false, viewMatrix.elements);
    gl.drawArrays(gl.TRIANGLES, 0, 9);
  };
  draw();

  document.addEventListener('keydown', e => {
    switch (e.keyCode) {
      case 39:
        g_near += 0.01;
        break;
      case 37:
        g_near -= 0.01;
        break;
      case 38:
        g_far += 0.01;
        break;
      case 40:
        g_far -= 0.01;
        break;
    }
    draw();
  });
});

const v_shader_source = `
  attribute vec4 a_Position;
  attribute vec4 a_Color;
  uniform mat4 u_ProjMatrix;
  varying vec4 v_Color;
  void main(){
    gl_Position = u_ProjMatrix * a_Position;
    v_Color = a_Color;
  }
`;

const f_shader_source = `
  precision lowp float;
  varying vec4 v_Color;
  void main(){
    gl_FragColor = v_Color;
  }
`;